package com.example.mallapi.config;/*
@author name
@data 2023/5/31-19:20
*/

import com.example.mallapi.interceptor.CheckTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 跨域问题处理
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${upload.path}")
    private String uploadPath;

    @Autowired
    private CheckTokenInterceptor checkTokenInterceptor;


    //解决跨域问题
    @Bean
    public CorsFilter corsFilter(){
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        //设置访问源地址
        config.addAllowedOriginPattern("*");
        //设置访问源请求头
        config.addAllowedHeader("*");
        //设置访问源请求方法
        config.addAllowedMethod("*");
        //有效期1800秒
        config.setMaxAge(1800L);
        //添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",config);
        //返回新的CorsFilter
        return new CorsFilter(source);
    }

    /**
     * 配置拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration interceptor = registry.addInterceptor(checkTokenInterceptor);

        interceptor.addPathPatterns("/**")
                .excludePathPatterns("/login")
                .excludePathPatterns("/captcha")
                .excludePathPatterns("/img_mall/**");
    }

    //配置资源真实路径
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/img_mall/**")     //当请求upload/**时 指定资源真实位置:uploadPath
                .addResourceLocations("file:" + uploadPath);   //访问本地磁盘文件  所以路径前＋file：
    }
}

/**
 * 当存在跨域是 服务型需要的token在8080中
 * 而端口666中并没有token，所以被服务器这边拦截
 *
 * 解决：设置/img_mall/** 该请求不被服务器拦截
 */